package com.lance.answer.question_answer.xj_new.tmp;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CourseInfo;
import com.lance.answer.dto.XjCourseVideoInfo;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author fengx
 * 新疆一体化答题 按课程答题
 * 管理学基础
 * 基础汉语(1)
 * 个人与团队管理
 * 公共政策概论
 * 社会调查研究与方法
 * // 38903 形势与政策补考------------2022-05-28
 * fixme 2022-6-9 给特殊课程使用？？？？？？？？？？测验个数和视频个数 没有规律的
 */
@Slf4j
public class BatchDoXJAnswer {

    final static Object lock = new Object();


    public static void main(String[] args) throws Exception {

        List<String> vip = Lists.newArrayList(
                "513902198505077187"

        );

    //    Thread.sleep(1000*60*60*7);
      //  Thread.sleep(5*60*60*1000);
        //是否提交答案
        // 视频的数量 和作业数量是否相等 （是否有导论），相等就是true
        //并发开启的浏览器数量
        int sync = 6;
        //驱动路径
        String driverPath = "d:\\ynouAutoStudy\\chromedriver.exe";
        //初始化日志配置
        //初始化日志配置
        Constant.initLog();

        //预加载所有用户信息
      //  InputStream inputStream3 = new FileInputStream("E:\\一体化2022.user");
        InputStream inputStream3 = new FileInputStream("E:\\alluser.txt");
        List<String> allUsers = IOUtils.readLines(inputStream3, "utf-8");
        Map<String, String> usernameAndPwd = Maps.newHashMap();

        for (String user : allUsers) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            String pwd = strs[1];
            if (pwd.length() > 14) {
                if (pwd.contains("X")) {
                    pwd = userCode.substring(11, 17);
                } else {
                    pwd = userCode.substring(12);
                }
            }
            usernameAndPwd.put(userCode.toUpperCase(Locale.ROOT), pwd);
        }


        InputStream inputStream = new FileInputStream("E:\\排名map.txt");
        List<String> allKeyValues = IOUtils.readLines(inputStream, "utf-8");
        Map<String, String> mapTmp = Maps.newHashMap();
        for (String keyValues : allKeyValues) {
            String[] strs = keyValues.split("&");
            String k1 = strs[0];
            String v1 = strs[1];
            mapTmp.put(k1, v1);
        }

        //加载所有课程配置
        List<CourseInfo> courseList = Lists.newArrayList();
        for (File file : new File("E:\\XjStudentCourseInfoTmp\\names").listFiles()) {
            String fileName = file.getName();
            String code = fileName.substring(0, fileName.length() - 5);
            CourseInfo courseInfo = new CourseInfo();
            courseInfo.setOpenCourseId(Integer.parseInt(code));
            courseInfo.setSubjectName(mapTmp.get(code));

            File file1 = new File("D:\\新疆一体化视频作业\\" + code + "\\" + mapTmp.get(code) + "（视频作业）.json");
            if (!file1.exists()) {
                continue;
            }
            courseList.add(courseInfo);
        }
        Collections.sort(courseList);

        //加载每个课程答案
        for (CourseInfo info : courseList) {
            //获取模板路径,通过流的方式获取文件可以避免被打成jar包之后无法获取文件路径的异常
            String subjectName = info.getSubjectName();
            int openCourseId = info.getOpenCourseId();
            InputStream inputStream1 = new FileInputStream("D:\\新疆一体化视频作业\\" + openCourseId + "\\" + subjectName + "（视频作业）.json");
            String answerStr = IOUtils.toString(inputStream1, StandardCharsets.UTF_8);
            List<AnswerObject> listAnswerObject = JSONObject.parseArray(answerStr, AnswerObject.class);
            Map<String, AnswerObject> answerMap = Maps.newHashMap();
            for (AnswerObject answerObject : listAnswerObject) {
                answerMap.put(DealJsonString.delHTMLTag(Util.dealContent(answerObject.getQuestionTitle())), answerObject);
            }
            info.setAnswerMap(answerMap);

        }




        //加载用户答题参数
        LinkedBlockingDeque<CourseInfo> userCourseQueue = new LinkedBlockingDeque<>();
        for (CourseInfo courseInfo : courseList) {
            try {
                InputStream inputStream4 = new FileInputStream("E:\\XjStudentCourseInfoTmp\\names\\" + courseInfo.getOpenCourseId() + ".json");
                String userStr = IOUtils.toString(inputStream4, StandardCharsets.UTF_8);

             //   InputStream inputStream22 = new FileInputStream("D:\\新疆一体化2\\CourseInfoDeal\\" + courseInfo.getOpenCourseId() + ".json");
                InputStream inputStream22 = new FileInputStream("D:\\新疆一体化3\\CourseInfoDeal\\" + courseInfo.getOpenCourseId() + "\\"+courseInfo.getSubjectName()+".json");
                String videoInfoStr = IOUtils.toString(inputStream22, StandardCharsets.UTF_8);
                XjCourseVideoInfo xjCourseVideoInfo = JSONObject.parseObject(videoInfoStr, XjCourseVideoInfo.class);

                int examinesSize = 0;
                int resourcesSize = 0;
                for (XjCourseVideoInfo.ContentDTO contentDTO : xjCourseVideoInfo.getContent()) {
                    examinesSize = examinesSize + contentDTO.getExamines().size();
                    resourcesSize = resourcesSize + contentDTO.getResources().size();
                }
                boolean equals;
                if (examinesSize == resourcesSize||resourcesSize<1) {
                    continue;
                } else  {
                    equals = false;
                }


                // 当前这门课程所有的
                List<String> users = JSONObject.parseArray(userStr, String.class);
                for (String s : users) {
                    String pwd = usernameAndPwd.get(s.toUpperCase(Locale.ROOT));
                    CourseInfo courseInfo1 = new CourseInfo();
                    courseInfo1.setAnswerMap(courseInfo.getAnswerMap());
                    courseInfo1.setOpenCourseId(courseInfo.getOpenCourseId());
                    courseInfo1.setSubjectName(courseInfo.getSubjectName());
                    courseInfo1.setPwd(pwd);
                    courseInfo1.setUser(s);
                    courseInfo1.setXjCourseVideoInfo(xjCourseVideoInfo);
                    courseInfo1.setEqulas(equals);

                    if(
                        // 公共行政学
                            courseInfo1.getOpenCourseId() == 39088
                                    //  金融基础知识
                           || courseInfo1.getOpenCourseId() == 39519
                    ){
                        continue;
                    }
//                    if(!vip.contains(s)){
//                        continue;
//                    }
//                    if(!"620123200203187728".equals(s)){
//                        continue;
//                    }
                    System.err.println("??????????????????"+courseInfo1);

                    // c??????????????????????FIXME
                    // 城市管理学
                    if(courseInfo1.getOpenCourseId()!=38996){
                        continue;
                    }
                    userCourseQueue.addLast(courseInfo1);

                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        log.info("userCourseQueueSize:{}", userCourseQueue.size());


        for (int i = 1; i <= sync; i++) {
            Thread answerThread = new BatchDoXJAnswerTask(driverPath, userCourseQueue);
            //log.info("加载课程ID：{} 名称：{} ", openCourseId,subjectName);
            answerThread.setName("答题线程--" + i);
            answerThread.start();
        }

    }

}
